import React, { useState, useContext, useEffect } from "react";
import Box from "./Box";
import Text from "./Text";
import Button from "./Button";
import Modal from "./Modal";
import { NotificationContext } from "./Notifications";
import { getMagicPoints, addMagicPoints } from "./UserMagic";

// 检查是否在浏览器环境
const isBrowser = typeof window !== 'undefined';

const DownloadConfirmModal = ({ 
  isOpen, 
  onClose, 
  onConfirm, 
  torrentName, 
  averageRating, 
  magicCost 
}) => {
  const { addNotification } = useContext(NotificationContext);
  const [loading, setLoading] = useState(false);
  const [currentMagicPoints, setCurrentMagicPoints] = useState(0);
  
  // 使用useEffect获取魔力值，确保在客户端渲染时执行
  useEffect(() => {
    if (isOpen && isBrowser) {
      setCurrentMagicPoints(getMagicPoints());
    }
  }, [isOpen]);
  
  const handleConfirmDownload = () => {
    if (!isBrowser) return;
    
    setLoading(true);
    const currentMagic = getMagicPoints();
    
    // 仍然检查魔力值是否足够，但不再显示弹窗提示
    if (currentMagic < magicCost) {
      setLoading(false);
      onClose();
      // 直接执行下载，不再显示积分不足的提示
      onConfirm();
      return;
    }
    
    // 扣除魔力值
    addMagicPoints(-magicCost, `下载种子：${torrentName}`);
    addNotification("success", `成功扣除${magicCost}点魔力值`);
    setLoading(false);
    onConfirm();
  };
  
  return (
    <Modal isOpen={isOpen} onClose={onClose}>
      <Box p={4}>
        <Text as="h3" mb={3}>下载确认</Text>
        <Text mb={3}>您即将下载种子：<strong>{torrentName}</strong></Text>
        <Text mb={3}>
          此种子需要扣除 <strong>{magicCost}</strong> 点魔力值。
        </Text>
        <Text mb={4}>您当前的魔力值：<strong>{currentMagicPoints}</strong></Text>
        
        <Box display="flex" justifyContent="flex-end">
          <Button variant="secondary" onClick={onClose} mr={3} disabled={loading}>
            取消
          </Button>
          <Button onClick={handleConfirmDownload} disabled={loading}>
            {loading ? "处理中..." : "确认下载"}
          </Button>
        </Box>
      </Box>
    </Modal>
  );
};

export default DownloadConfirmModal; 